import { API_BASEURL } from "@/common/utils/config.js"
import { ApiOauthTokenLogin } from './api/user.js'
let http = {
    post:'',
    get:'',
		downloadFile:''
}

let header = {
	'X-Requested-With': 'XMLHttpRequest',
	'Authorization': 'Basic c3dvcmQ6c3dvcmRfc2VjcmV0'
};

let baseUrl = API_BASEURL

http.get = (api,data) => {
	let token = uni.getStorageSync('token')
	if (token) {
		header['blade-auth'] = token
	}else{
		header['blade-auth'] = ''
	}
	header['Accept'] = 'application/json'
	header['Content-Type'] = 'application/json; charset=UTF-8'
	return new Promise((resolve, reject) => {
				uni.request({
					url: baseUrl + api,
					data: data,
					method: 'get',
					header,
					dataType: 'json',
					success(res) {
						if(res.statusCode === 200 || res.statusCode === 1 || res.statusCode === 400) {
							resolve(res.data)
						} else if (res.statusCode === 401) {
							const loginEffectTime = uni.getStorageSync('loginEffectTime') || 0
							if(!uni.getStorageSync('refresh_token') || !uni.getStorageSync('token')){
								uni.reLaunch({
									url: '../../pages/user/login'
								});
							}else{
								if(loginEffectTime - new Date().getTime() < 600){
									uni.removeStorageSync('token')
									uni.reLaunch({
										url: '../../pages/user/login'
									});
								}else{
									const login = async () =>{
										const res = await ApiOauthTokenLogin({
											grant_type:'refresh_token',
											tenantId:'000',
											refresh_token:uni.getStorageSync('refresh_token')
										})
										if (res.access_token){
											// uni.setStorageSync('storeId', '210105001093');
											uni.setStorageSync('token', res.token_type +' '+res.access_token);
											uni.setStorageSync('refresh_token', res.refresh_token);
											uni.setStorageSync('loginEffectTime', new Date().getTime()+res.expires_in*1000)
											uni.setStorageSync('userInfo',res);
											 const resp = await http.get(api,data)
											 return resp
										}
									}
									resolve(login())
								}
							}
							
						} else {
							reject()
							uni.showModal({
								content: res.data.msg,
								showCancel: false
							});
						}
					},
					fail(err) {
						reject()
						uni.showModal({
							content:"" + err.errMsg
						});
					}
				})
			})
}

http.post = (api,data,type) => {
	let token = uni.getStorageSync('token')
	if (token) {
		header['blade-auth'] = token
	}
	if(type==="json"){
		header['Accept'] = 'application/json'
		header['Content-Type'] = 'application/json; charset=UTF-8'
	}else{
		header['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
	}
	return new Promise((resolve, reject) => {
				uni.request({
					url: baseUrl + api,
					data: data,
					method: 'POST',
					header,
					dataType: 'json',
					success(res) {
						if(res.statusCode === 200 || res.statusCode === 1 || res.statusCode === 400) {
							resolve(res.data)
						} else if (res.statusCode === 401) {
							uni.showModal({
								title: '提示',
								content:"您的登录已过期,请重新登录",
								cancelText: '取消',
								confirmText: '确定',
								success: resp => {
									if (resp.confirm) {
										if (resp.confirm) {
											uni.removeStorageSync('token')
											uni.reLaunch({
												url: '../../pages/user/login'
											});
										}
									}
								}
							});
						} else {
							console.log(res)
							reject()
							uni.showModal({
								content: res.data.msg || res.data.error_description,
								showCancel: false
							});
						}
					},
					fail(err) {
						reject()
						uni.showModal({
							content:err
						});
					}
				})
	})
}


http.downloadFile = (api,data,type) =>{
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: baseUrl + api,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.openDocument({
						filePath: res.tempFilePath, 
					// 如果文件名包含中文，建议使用escape(res.tempFilePath)转码，防止ios和安卓客户端导致的差异
						success: function(res) {
							console.log('打开文档成功');
						}
					});
				}
			}
		});
	})
}
export default http